package com.saturdaycoder.volumeman;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class ProfileSwitchService extends Service {
	private final IBinder mBinder = new LocalBinder();
	
	private final ProfileSwitchTask switchTask = new ProfileSwitchTask();
	
	public class LocalBinder extends Binder {
		ProfileSwitchService getService() {
			return ProfileSwitchService.this;
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}
	
	@Override
	public void onCreate() {
		Debugger.info("SERVICE onCreate");
		super.onCreate();
	}
	
	@Override
	public void onDestroy() {
		Debugger.info("SERVICE onDestroy");
		super.onDestroy();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Debugger.info("SERVICE onStart(intent, " + flags + ", " + startId + ")");
		if (intent == null) {
			Debugger.warn("this is a re-delivery of previously killed service intent");
			stopSelf();
			return START_NOT_STICKY;
		}
		
		/*String action = intent.getAction();
		if (action == null || action.equals(VolumeMan.ACTION_SWITCH_PROFILE)) {
			Debugger.warn("invalid intent action");
			stopSelf();
			return START_NOT_STICKY;
		}*/
		
		int profileId = intent.getIntExtra(VolumeMan.EXTRA_PROFILE_INDEX, -1);
		if (profileId < 0 || profileId > 4) {
			Debugger.warn("profile id invalid");
			stopSelf();
			return START_NOT_STICKY;
		}
		
		switchTask.execute(profileId);
		return START_NOT_STICKY;
	}
	
	
	public class ProfileSwitchTask extends AsyncTask<Integer, Integer, Integer> {
		@Override
    	protected void onProgressUpdate(Integer... progress) {
			
		}
		
		@Override
        protected void onPostExecute(Integer result) {
			Debugger.warn("task completed. stop service");
			popNotify("Volume successfully changed");
			stopSelf();
		}
		
		@Override
    	protected void onCancelled() {
			Debugger.warn("task was cancelled. stop service");
			stopSelf();
		}
		
		@Override
    	protected Integer doInBackground(Integer... params) {
			if (params.length < 1) {
				Debugger.error("no input param for doInBackground");
				return -1;
			}
			int profileId = params[0];
			if (profileId < 0 || profileId > 4) {
				Debugger.error("invalid profileId in doInBackground");
				return -1;
			}
			
			Debugger.info("Switching to profile " + profileId);
			return 0;
		}
	}
	
    private void popNotify(String msg)
    {
        Toast.makeText(ProfileSwitchService.this, msg,
                Toast.LENGTH_LONG).show();
    }
}
